package com.itheima.gatewaywemedia;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关统一鉴权，判断用户是否登录
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.登录请求的白名单过滤
        //1.1获取请求对象，响应对象
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse res = exchange.getResponse();
        //1.2获取请求路径
        String path = req.getURI().getPath();
        log.info("请求了路径：{}"+path);
        //1.3对请求路径判断是否为登录的路径，是则放行
        if (path.startsWith("/wemedia/login")){
            return chain.filter(exchange);
        }
        //2.获取请求头中的token，校验token的有效性
        String token = req.getHeaders().getFirst("token");
        //2.1如果token有值
        if (!StringUtils.isEmpty(token)) {
            //2.2校验token的有效性
            int result =0;
            try {
                //claims是什么，是载荷
                Claims claims = AppJwtUtil.getClaimsBody(token);
                //获取载荷中登录用户的id？为什么？原因是登录成功时，是通过用户id来生成token的
                //看WmUserServiceImpl.loginCheck方法 第72行
                Long loginUserId = claims.get("id", Long.class);
                //存入请求头
                req.mutate().header(SystemConstants.USER_HEADER_NAME,loginUserId.toString());
                result = SystemConstants.JWT_OK;
            } catch (ExpiredJwtException ex) {
                result = SystemConstants.JWT_EXPIRE;
            } catch (Exception e) {
                result = SystemConstants.JWT_FAIL;
            }

            if (SystemConstants.JWT_OK== result) {
                //3.如果有效则放行
                return chain.filter(exchange);
            }
        }
        //4.无token或无效则拒绝，返回401
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
